import { Card, Checkbox, Button } from 'antd-mobile'
import React, { ReactElement, useState, useEffect, useCallback } from 'react'
import styles from './index.less'
import { CartProductType, ConnectProps, ConnectState, CartModelState } from '@/models/types'
import { connect, history } from 'umi'

interface Props extends ConnectProps {
    data: CartProductType[],
    trackCheckedAll: Function,
    cart: CartModelState

}

function PayBar({ data, trackCheckedAll, dispatch, cart }: Props): ReactElement {

    const allChecked = data.every(item => item.checked === true)

    /**不能同步执行setstate */
    const [checked, setchecked] = useState(false)

    let checkedData: CartProductType[] = data.filter(item => item.checked === true)
    let sum: number
    if (checkedData.length) {
        sum = checkedData.length && checkedData.map(item => Number(+item.price * item.count)).reduce((a, b) => a + b)
    } else {
        sum = 0
    }
    const checkAllHandle = useCallback(() => {
        setchecked(!checked)
    }, [checked])


    useEffect(() => {
        trackCheckedAll(checked)
    }, [checked])
    const goPay = () => {

        dispatch({ type: 'cart/saveCart', payload: { data: checkedData } })
        history.push('/confirmBill')
    }
    /**
     * Card
     *  CheckboxItem
     *      onChange
     *      checked
     */
    return (
        <Card full className={styles.main}>
            <Checkbox.CheckboxItem
                onChange={checkAllHandle}
                checked={allChecked}
            >
                全选
            </Checkbox.CheckboxItem>
            <span>合计： ¥ <span>{sum.toFixed(2)}</span></span>
            <Button type='primary' className={styles.btn} onClick={goPay}>去结算</Button>
        </Card>
    )
}
export default connect(({ cart }: ConnectState) => ({ cart }))(PayBar)